package com.diy.sigmund.diycommon.spring.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 获得端口的配置，启动时无法拿到，启动后调用接口可以拿到
 *
 * @author ylm-sigmund
 * @since 2021/8/27 17:02
 */
@Component
public class PortConfig {

    private static final Logger log = LoggerFactory.getLogger(PortConfig.class);

    /**
     * 采用随机端口的时候${server.port}获取的是0,无法满足要求 @Value("${server.port}")
     *
     * @LocalServerPort 外部化配置其实是有点不靠谱的, 它并非完全静态, 也不一定及时返回
     */
    // @LocalServerPort
    // private int port;

    @Autowired
    private Environment environment;

    /**
     * 技巧以解决 Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'local.server.port' in value
     * "${local.server.port}"
     *
     * @return
     */
    public String getPort() {
        return environment.getProperty("local.server.port");
    }
}
